package o2o.utils;

import com.jinyou.utils.common.Geohash;
import com.jinyou.utils.common.ValidateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2019/8/15 19:46
 * @Classname: CommonUtils
 * @To change this template use File | Settings | File Templates.
 */
public class CommonUtils {

    public static <T> Set<T> splitToSet(String param, Class<T> clazz) {
        return splitToSet(param, clazz, null);
    }

    /**
     * @param param
     * @param clazz
     * @param <T>
     * @return
     * @desc 将拼接的字符串截取后转乘指定的类型
     */
    public static <T> Set<T> splitToSet(String param, Class<T> clazz, String splitKey) {
        if (StringUtils.isEmpty(param)) {
            return Collections.EMPTY_SET;
        }
        if (splitKey == null) {
            splitKey = ",";
        }
        String part[] = param.split(splitKey);
        return (Set<T>) Arrays.stream(part).filter(a -> StringUtils.isNotEmpty(a)).map(a -> {
            if (clazz == Integer.class) {
                return Integer.parseInt(a.toString());
            }
            if (clazz == Long.class) {
                return Long.parseLong(a.toString());
            }
            if (clazz == Double.class) {
                return Double.parseDouble(a.toString());
            }
            if (clazz == String.class) {

            }
            // .... 其他类型  自行处理
            return (T) (a);
        }).collect(Collectors.toSet());
    }

    /**
     * @param lnglats
     * @param lng
     * @param lat
     * @return
     * @desc 判断点是不是在电子围栏范围内
     */
    public static boolean isInFenceRange(String lnglats, Double lng, Double lat) {
        if (StringUtils.isEmpty(lnglats) || ValidateUtil.isNotLatLng(lat, lng)) {
            return false;
        }
        String[] split = StringUtils.split(lnglats, ";");
        List<Double> lngList = new ArrayList<>();
        List<Double> latList = new ArrayList<>();
        for (int j = 0; j < split.length; j++) {
            try {
                String[] lnla = split[j].split(",");
                Double tempLng = Double.parseDouble(lnla[0]);
                Double tempLat = Double.parseDouble(lnla[1]);
                lngList.add(tempLng);
                latList.add(tempLat);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        Double[] lngArr = lngList.toArray(new Double[lngList.size()]);
        Double[] latArr = latList.toArray(new Double[latList.size()]);
        return Geohash.isInPolygon(lng, lat, lngArr, latArr);
    }

    /**
     * 获取当前线程的请求信息
     *
     * @param key 请求参数名称
     * @return
     */
    public static Object getReqParamVal(String key) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return getReqParamVal(request, key);
    }

    /**
     * 获取当前线程的指定请求信息
     *
     * @param key
     * @return
     */
    public static Object getReqParamVal(HttpServletRequest httpRequest, String key) {
        if (key == null) {
            throw new RuntimeException("this request key not allow empty");
        }
        String val = httpRequest.getHeader(key);
        if (val == null) {
            val = httpRequest.getParameter(key);
        }
        return val;
    }


    /**
     * @param str          // 传入的固定字符串
     * @param index        // 开始的下标
     * @param generateSize // 生成多少个
     * @param maxDigit     // 生成的位数
     * @param step         //  步长
     * @param codeList     // 返回的列表
     * @return //   最后序列号
     */
    public static Integer generateExchangeCode(String str, int index, int generateSize, int maxDigit, int step, List<String> codeList) {
        str = str.replaceAll("-", "");
        int length = str.length();
        if (length > maxDigit) {
            return index;
        }
        int max = getGenerateMax(str, maxDigit);
        for (int i = 0; i < generateSize; i++) {
            index = index + (new Random().nextInt(step) + 1);
            if (index > max) {
                return index;
            }
            codeList.add(getGenerateCode(str, String.valueOf(index), maxDigit));
        }
        return index;
    }

    /**
     * 生成指定长度的数字串
     *
     * @param str
     * @param indexStr
     * @param maxDigit
     * @return
     */
    private static String getGenerateCode(String str, String indexStr, int maxDigit) {
        StringBuilder builder = new StringBuilder();
        builder.append(str);
        int length = maxDigit - (str.length() + indexStr.length());
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                builder.append("0");
            }
        }
        builder.append(indexStr);
        return builder.toString();
    }

    /**
     * 根据位数获取最大的序列
     *
     * @param str
     * @param maxDigit
     * @return
     */
    private static int getGenerateMax(String str, int maxDigit) {
        int length = str.length();
        int max = 1;
        if (maxDigit > length) {
            for (int i = 0; i < (maxDigit - length); i++) {
                max = max * 10;
            }
        }
        return (max - 1);
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Integer index = generateExchangeCode("20-10", 0, 10, 10, 10, list);
        System.out.println("index--->" + index);
        System.out.println(list.size());
        list.forEach(item -> System.out.println(item));
    }

}
